// JointFormerManager.cpp: implementation of the JointFormerManager class.
//
//////////////////////////////////////////////////////////////////////

#include "stdafx.h"
#include "JointFormerManager.h"
#include "ProjectManager.h"
#include "OriginalPropertySet.h"
#include "FunctionFormerManager.h"
#include "PHSDirectorySetting.h"
#include "PHSApp.h"

//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
using namespace PropertySystem;

IMPLEMENT_SINGLETON(JointFormerManager);

JointFormerManager::JointFormerManager()
{
	m_strRegularSetTableName = _T("JPFormat_Matching_Rule");
	m_strJointPropertyTable = _T("Joint_Property");
	m_strJointFunctionTable = _T("Joint_Function");

	ASSERT(GetProjectManager().CurProject());
	
	Project* pPrj = GetProjectManager().CurProject();
	m_strDBPath = GetCurDirectorySetting().PrjTemplateDir() + GetPHSApp()->JointFormerName();

}

JointFormerManager::~JointFormerManager()
{

}

JointFormer* JointFormerManager::GetJointFormer(INT nFirstStyle, INT nSecondStyle)
{
	CString strKey;
	strKey.Format(_T("%d_%d"), nFirstStyle, nSecondStyle);

	JointFormer* pFormer = GetManaged(strKey);
	if(pFormer != NULL)
		return pFormer;

	pFormer = NewFormer(nFirstStyle, nSecondStyle);
	if(pFormer != NULL)
		Add(strKey, pFormer);

	return pFormer;
}

void JointFormerManager::GetFormerProperty(JointFormer* pFormer)
{
	OriginalPropertySet set;
	set.GetOriginalPropertySet(pFormer->ID(), m_strJointPropertyTable, m_strDBPath);

	OriginalProperty* pVar = set.GetFirst();
	while(pVar != NULL)
	{
		pFormer->GetPropertyStack().AddProperty(pVar->GenerateVariable());
		pVar = set.GetNext();
	}
}

void JointFormerManager::GetFormerFunction(JointFormer* pFormer)
{
	FunctionFormerManager manager;
	manager.GetFunctionSet(pFormer->ID(), m_strJointFunctionTable, m_strDBPath);

	FunctionObject* pObj = manager.GetFirstFunction();
	while(pObj != NULL)
	{
		pFormer->GetFunctionStack().AddFunction(pObj);
		pObj = manager.GetNextFunction();
	}
	manager.CloseFunctionSet();
}

JointFormer* JointFormerManager::NewFormer(INT nFirstStyle, INT nSecondStyle)
{
	JointFormer* pFormer = NULL;
	CString strSql;
	strSql.Format(_T("select * from %s where JPF_Matched = '%d' \
		and JPF_Matching = '%d'"), m_strRegularSetTableName, nFirstStyle, nSecondStyle);

	_RecordsetPtr rs;
	try
	{
		const _ConnectionPtr& pCon = *DBConnectionManager::Instance()
			->GetConnectionPtrByUri(m_strDBPath);
		rs = pCon->Execute(_bstr_t(strSql), NULL, adCmdText);
		if(rs == NULL)
		{
			return NULL;
		}
		if(!rs->adoEOF && !rs->BOF)
		{
			pFormer = new JointFormer;
			pFormer->ID(vtoi(rs->GetCollect(_T("ID"))));
			pFormer->FirstJointTypeID(vtoi(rs->GetCollect(_T("JPF_Matched"))));
			pFormer->NextJointTypeID(vtoi(rs->GetCollect(_T("JPF_Matching"))));
		}
		rs->Close();
	}
	CATCH_COM_ERROR(rs, NULL);

	GetFormerFunction(pFormer);
	GetFormerProperty(pFormer);

	return pFormer;
}